from django.db import models

# Create your models here.


class BaseModel(models.Model):
    is_delete = models.BooleanField(default=False)
    create_time = models.DateTimeField(auto_now_add=True)
    last_update_time = models.DateTimeField(auto_now=True)

    class Meta:
        # 单个字段，有索引，有唯一
        # 多个字段，有联合索引，联合唯一
        # unique_together
        # index_together
        abstract = True  # 不会创建这张表


class Book(BaseModel):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32, verbose_name='书名', help_text='这里写书名')  # verbose_name admin中显示
    price = models.DecimalField(max_digits=5, decimal_places=2)
    # db_constraint=False 逻辑上的外键关联，实质上没有外键练习，增删改不会受外键影响，orm查询不影响
    publish = models.ForeignKey(to='Publish', on_delete=models.DO_NOTHING, db_constraint=False)
    authors = models.ManyToManyField(to='Author', db_constraint=False)

    def __str__(self):
        return self.name

    @property
    def publish_name(self):
        return self.publish.name

    def author_list(self):
        return [{'name': author.name, 'sex': author.get_sex_display()} for author in self.authors.all()]

    class Meta:
        verbose_name_plural = '书'  # admin中表名的显示


class Publish(BaseModel):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=32)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = '出版社'


class Author(BaseModel):
    name = models.CharField(max_length=32)
    sex = models.IntegerField(choices=((1, '男'), (2, '女')))
    # OneToOneField 默认就是ForeignKey + unique
    authordetail = models.OneToOneField(to='AuthorDetail', db_constraint=False, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = '作者'


class AuthorDetail(BaseModel):
    mobile = models.CharField(max_length=11)

    class Meta:
        verbose_name_plural = '作者详情'
